package com.yy.controller.loginRegister;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yy.common.core.AjaxResult;
import com.yy.common.core.model.UserVM;
import com.yy.common.utils.DateUtils;
import com.yy.common.utils.JwtHelper;
import com.yy.common.utils.MD5Util;
import com.yy.common.utils.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import com.yy.pojo.User;
import com.yy.pojo.UserRest;
import com.yy.service.UserRestService;
import com.yy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

@RestController
@RequestMapping("")
public class LoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserRestService userRestService;
    @Autowired
    private JwtHelper jwtHelper;

    @PostMapping("/main/login")
    public AjaxResult login(@RequestBody User user) {
        User u = userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getUserName,user.getUserName()));
        if (u == null) {
            return AjaxResult.error("用户不存在");
        } else {
            if (u.getPassword().equals(MD5Util.encrypt(user.getPassword()))) {
                u.setLoginDate(DateUtil.date());
                userService.updateById(u);
                UserVM userVM = new UserVM();
                BeanUtil.copyProperties(u, userVM);
                userVM.setLoginDate(DateUtil.formatDateTime(u.getLoginDate()));
                String token = jwtHelper.createToken(u.getUserId());
                return AjaxResult.success(userVM).put("token", token);
            } else {
                return AjaxResult.error("密码错误");
            }
        }
    }
    @GetMapping("main/login/{id}")
    public AjaxResult requestRestaurantManager(@PathVariable("id") Long id) {
        UserRest userRest = userRestService.getOne(Wrappers.lambdaQuery(UserRest.class).eq(UserRest::getUserId,id));
        return AjaxResult.success(userRest.getRestId());
    }

    @GetMapping("main/tokenCheck")
    public AjaxResult tokenCheck(@RequestHeader("token")String token) {
        if (!jwtHelper.isExpiration(token)) {
            Long userId = jwtHelper.getUserId(token);
            String newToken = jwtHelper.createToken(userId);
            return AjaxResult.success().put("token",newToken);
        }
        return AjaxResult.error();
    }
}
